package com.yidi.system.service.imp;

import com.yidi.common.constant.Constants;
import com.yidi.common.constant.UserConstants;
import com.yidi.common.core.domain.TreeSelect;
import com.yidi.common.core.domain.entity.SysMenu;
import com.yidi.common.core.domain.entity.SysRole;
import com.yidi.common.core.domain.entity.SysUser;
import com.yidi.common.core.service.imp.AbstractBaseService;
import com.yidi.common.enums.RemoveEnum;
import com.yidi.common.utils.SecurityUtils;
import com.yidi.common.utils.StringUtils;
import com.yidi.system.domain.vo.MetaVo;
import com.yidi.system.domain.vo.RouterVo;
import com.yidi.system.repository.SysMenuRepository;
import com.yidi.system.repository.SysRoleMenuRepository;
import com.yidi.system.service.SysMenuService;
import com.yidi.system.service.SysRoleService;
import com.yidi.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ：Xn
 * @ClassName: SysMenuServiceImpl
 * @date ：2021-10-19 14:38
 * @describe ：
 */
@Service
public class SysMenuServiceImpl extends AbstractBaseService<SysMenu> implements SysMenuService {

    @Autowired
    private SysMenuRepository sysMenuRepository;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysRoleMenuRepository sysRoleMenuRepository;
    @PersistenceContext
    private EntityManager em;

    /**
     * 查询系统菜单列表
     *
     * @param menu 菜单信息
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuList(SysMenu menu, Long userId)
    {
        List<SysMenu> menuList = null;
        SysUser user = sysUserService.findById(userId);
        // 管理员显示所有菜单信息
        if (SysUser.isAdmin(user.getUserName()))
        {
            menuList = selectMenuList(menu);
        }
        else
        {
            List<Map<String, Object>> maps = sysMenuRepository.selectMenuListByUserId(userId, menu.getMenuName(), menu.getVisible(), menu.getStatus());
            menuList = mapChangeMenus(maps);
        }
        return menuList;
    }

    /**
     * 根据角色ID查询菜单树信息
     *
     * @param roleId 角色ID
     * @return 选中菜单列表
     */
    @Override
    public List<Integer> selectMenuListByRoleId(Long roleId)
    {
        SysRole role = sysRoleService.findById(roleId);
        StringBuilder sql = new StringBuilder(
                "select m.id from sys_menu m left join sys_role_menu rm on m.id = rm.menu_id where");
        if(roleId != null){
            sql.append(" rm.role_id = ").append(roleId);
        }

        if(role.isMenuCheckStrictly()){
            sql.append(" and m.id not in (select m.parent_id from sys_menu m inner join sys_role_menu rm on m.id = rm.menu_id and rm.role_id = ").append(roleId).append(")");
        }

        sql.append(" order by m.parent_id, m.order_num");

        Query query = em.createNativeQuery(sql.toString());
        List resultList = query.getResultList();
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i < resultList.size(); i++){
            String num = resultList.get(i).toString();
            list.add(Integer.valueOf(num));
        }
        return list;
    }

    /**
     * 条件查询
     * @param menu
     * @return
     */
    public List<SysMenu> selectMenuList(SysMenu menu)
    {
        List<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.ASC, "parentId"));
        orders.add(new Sort.Order(Sort.Direction.ASC, "orderNum"));
        Sort sort = Sort.by(orders);

        List<SysMenu> dList = sysMenuRepository.findAll((root, query, cb) ->{
            List<Predicate> list = new ArrayList<>();
            list.add(cb.and(cb.equal(root.get("removeStatus").as(Integer.class), RemoveEnum.NOT_REMOVE.getCode())));

            if(StringUtils.isNotBlank(menu.getMenuName())) {
                list.add(cb.and(cb.like(root.get("menuName").as(String.class), menu.getMenuName())));
            }

            if(StringUtils.isNotBlank(menu.getStatus())){
                list.add(cb.and(cb.equal(root.get("status").as(String.class), menu.getStatus())));
            }

            Predicate[] p = new Predicate[list.size()];
            return cb.and(list.toArray(p));
        },sort);

        return dList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus)
    {
        List<SysMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    @Override
    public List<SysMenu> buildMenuTree(List<SysMenu> menus)
    {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysMenu dept : menus)
        {
            tempList.add(dept.getId());
        }
        for (Iterator<SysMenu> iterator = menus.iterator(); iterator.hasNext();)
        {
            SysMenu menu = (SysMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId()))
            {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户名称
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuTreeByUserId(Long userId)
    {
        List<SysMenu> menus = null;
        if (SecurityUtils.isAdmin(userId))
        {
            List<Map<String, Object>> treeAll = sysMenuRepository.selectMenuTreeAll();
            menus = mapChangeMenus(treeAll);
        }
        else
        {
            List<Map<String, Object>> userMenu = sysMenuRepository.selectMenuTreeByUserId(userId);
            menus = mapChangeMenus(userMenu);
        }
        return getChildPerms(menus, 0);
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterVo> buildMenus(List<SysMenu> menus)
    {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (SysMenu menu : menus)
        {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
            List<SysMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType()))
            {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            }
            else if (isMenuFrame(menu))
            {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            else if (menu.getParentId().intValue() == 0 && isInnerLink(menu))
            {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/inner");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = StringUtils.replaceEach(menu.getPath(), new String[] { Constants.HTTP, Constants.HTTPS }, new String[] { "", "" });
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public String checkMenuNameUnique(SysMenu menu)
    {
        Long menuId = StringUtils.isNull(menu.getId()) ? -1L : menu.getId();
        SysMenu info = sysMenuRepository.findByMenuNameAndParentId(menu.getMenuName(), menu.getParentId());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != menuId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 是否存在菜单子节点
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean hasChildByMenuId(Long menuId)
    {
        int result = sysMenuRepository.hasChildByMenuId(menuId);
        return result > 0 ? true : false;
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean checkMenuExistRole(Long menuId)
    {
        int result = sysRoleMenuRepository.checkMenuExistRole(menuId);
        return result > 0 ? true : false;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByUserId(Long userId)
    {
        List<String> perms = sysMenuRepository.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId)
    {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext();)
        {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SysMenu> list, SysMenu t)
    {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t)
    {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext())
        {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().equals(t.getId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu)
    {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu))
        {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu)
    {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu))
        {
            routerPath = StringUtils.replaceEach(routerPath, new String[] { Constants.HTTP, Constants.HTTPS }, new String[] { "", "" });
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame()))
        {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu))
        {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenu menu)
    {
        return menu.getParentId() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenu menu)
    {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu)
    {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu))
        {
            component = menu.getComponent();
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu))
        {
            component = UserConstants.INNER_LINK;
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu))
        {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenu menu)
    {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    public List<SysMenu> mapChangeMenus(List<Map<String, Object>> menuMap){

        List<SysMenu> menuList  = new LinkedList<SysMenu>();

        for(int i = 0; i < menuMap.size(); i++) {
            Map<String, Object> map = menuMap.get(i);
            SysMenu m = new SysMenu();
            m.setId(Long.valueOf(String.valueOf(map.get("id"))));
            m.setParentId(Long.valueOf(String.valueOf(map.get("parentId"))));
            m.setMenuName(String.valueOf(map.get("menuName")));
            m.setPath(String.valueOf(map.get("path")));
            Object component = map.get("component");
            m.setComponent(component == null ? null : String.valueOf(component));
            m.setQuery(String.valueOf(map.get("query")));
            m.setVisible(String.valueOf(map.get("visible")));
            m.setStatus(String.valueOf(map.get("status")));
            m.setPerms(String.valueOf(map.get("perms")));
            m.setIsFrame(String.valueOf(map.get("isFrame")));
            m.setIsCache(String.valueOf(map.get("isCache")));
            m.setMenuType(String.valueOf(map.get("menuType")));
            m.setIcon(String.valueOf(map.get("icon")));
            m.setOrderNum(Integer.valueOf(String.valueOf(map.get("orderNum"))));
            menuList.add(m);
        }

        return menuList;
    }
}
